package library.client;

import java.util.ArrayList;
import java.util.List;

import javax.swing.table.AbstractTableModel;

import library.server.Author;
import library.server.Book;

public class LibraryTableModel extends AbstractTableModel {
	private static final long serialVersionUID = 1L;

	private static final int COLS_NUM = 6;

	private List<Book> filteredBooks, books;
	private String[] columnNames;
	private String filter;

	public LibraryTableModel(List<Book> books) {
		this.filteredBooks = books;
		this.books = books;
		this.filter = "";

		columnNames = new String[COLS_NUM];
		columnNames[0] = "ISDN";
		columnNames[1] = "Title";
		columnNames[2] = "Authors";
		columnNames[3] = "Publisher";
		columnNames[4] = "Date";
		columnNames[5] = "Price";
	}

	@Override
	public int getRowCount() {
		return filteredBooks.size();
	}

	@Override
	public int getColumnCount() {
		return COLS_NUM;
	}

	@Override
	public String getColumnName(int columnIndex) {
		return columnNames[columnIndex];
	}

	@Override
	public Class<?> getColumnClass(int columnIndex) {
		return getValueAt(0, columnIndex).getClass();
	}

	@Override
	public boolean isCellEditable(int rowIndex, int columnIndex) {
		return false;
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		switch (columnIndex) {
		case 0:
			return filteredBooks.get(rowIndex).getISDN();

		case 1:
			return filteredBooks.get(rowIndex).getTitle();

		case 2:
			String authors = "<HTML>";
			for (Author a : filteredBooks.get(rowIndex).getAuthors()) {
				authors += a.getName() + " " + a.getSurname() + "<br>";
			}
			authors += "</HTML>";
			return authors;

		case 3:
			return filteredBooks.get(rowIndex).getPublisher();

		case 4:
			return filteredBooks.get(rowIndex).getPublicationDate();

		case 5:
			return filteredBooks.get(rowIndex).getPrice();
		}
		return null;
	}

	public void setBooks(List<Book> books) {
		this.books = books;
		filteredBooks = filterBooks(books);
		fireTableDataChanged();
	}

	public void setFilter(String filter) {
		this.filter = filter;
		filteredBooks = filterBooks(books);
		fireTableDataChanged();
	}

	private List<Book> filterBooks(List<Book> bookToFilter) {
		if (filter.equals(""))
			return bookToFilter;
		else {
			List<Book> filteredBooks = new ArrayList<Book>();
			for (Book book : bookToFilter) {
				if(book.getTitle().contains(filter))
					filteredBooks.add(book);
			}
			return filteredBooks;
		}
	}
}
